package com.material.vtool.controller;

import com.material.vtool.entity.BUserDownloadInfoEntity;
import com.material.vtool.entity.reqEntity.SelectedMaterialBean;
import com.material.vtool.entity.respEntity.RespData;
import com.material.vtool.entity.respEntity.ReturnCode;
import com.material.vtool.service.UserDownloadInfoService;
import com.material.vtool.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/log")
public class UserDownloadInfoController {
    @Autowired
    private UserDownloadInfoService userDownloadInfoService;

    /**
     * 下载文章:保存文章下载日志
     * @param userId 下载用户ID
     * @param selectedMaterialBean 选中文章实体
     * @return
     */
    @PostMapping(value = "/materialDownload", produces = "application/json;charset=UTF-8")
    public RespData saveUserDownloadLog(@RequestHeader("userId") String userId, @RequestBody SelectedMaterialBean selectedMaterialBean) {
        if (selectedMaterialBean == null || selectedMaterialBean.getMaterialId() == null) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数错误");
        }

        Integer currentUserId = Integer.valueOf(userId);
        Integer materialId = selectedMaterialBean.getMaterialId();

        // 查看用户是否下载过该文章
        BUserDownloadInfoEntity bUserDownloadInfoEntity = userDownloadInfoService.getUserDownloadInfo(currentUserId, materialId);
        if (bUserDownloadInfoEntity != null) {
            bUserDownloadInfoEntity.setDownloadStatus(Integer.valueOf(1));
            bUserDownloadInfoEntity.setModifyTime(DateUtil.getCurDate());
            userDownloadInfoService.updateUserDownLoad(bUserDownloadInfoEntity);
        } else {
            userDownloadInfoService.saveUserDownloadLog(currentUserId, materialId);
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }
}
